<template>
  <div>
    <el-dialog
      class="develop-addmodal"
      v-model="visible"
      v-if="load"
      :title="title"
      :loading="loadings.form"
      width="1000px"
      draggable
      @close="close"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :z-index="2000"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-align="right"
        label-width="0"
        size="default"
        :label-position="
          handleType == 'view' || handleType == 'development-audit' ? 'right' : 'top'
        "
      >
        <div class="title-style"><span class="line"></span>基础信息</div>
        <Basic ref="basicRef" v-model:value="form" :handleType="handleType" />
        <div class="title-style"><span class="line"></span>推荐平台/站点</div>
        <div class="flex justify-between items-center mb-1">
          <div class="flex justify-start items-center">
            <template v-if="handleType !== 'view' && handleType !== 'development-audit'">
              <el-button class="mr-2" type="primary" @click="openProfitTrial()"
                >新增推荐平台/站点</el-button
              >
            </template>
          </div>
        </div>
        <Fee v-model="form.product_fee" @delFee="delFee" />
        <div class="title-style"><span class="line"></span>开发备注</div>
        <el-form-item label=" " label-width="0">
          <template v-if="handleType == 'view' || handleType == 'development-audit'">
            <template v-if="form.development_remark">
              <div v-html="form.development_remark"></div>
            </template>
            <template v-else>--</template>
          </template>
          <template v-else>
            <WangEditor v-model="form.development_remark" :min-height="100" />
          </template>
        </el-form-item>
        <div class="title-style">附件</div>
        <el-form-item label="" label-width="10px">
          <template v-if="handleType == 'view' || handleType == 'development-audit'">
            <template v-if="form.attachments">
              <div
                class="flex items-center"
                v-for="(item, index) in form.attachments"
                :key="index"
              >
                <svg-icon class="mr-2" icon-class="file" />{{ item.name }}
                <el-link class="ml-2" type="primary" @click="downloadUrl(item.url)"
                  >下载</el-link
                >
              </div>
            </template>
            <template v-else>--</template>
          </template>
          <template v-else>
            <FileUpload
              v-model="form.attachments"
              :limit="1"
              :isShowTip="false"
            ></FileUpload>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <span
          class="w-full flex justify-center relative py-2"
          v-if="handleType !== 'view' && handleType !== 'development-audit'"
        >
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="save()">保 存</el-button>
          <el-button
            type="primary"
            :loading="loading"
            @click="saveSubmit()"
            v-if="handleType != 'edit'"
            >保存并提交开发审核</el-button
          >
          <el-button
            type="primary"
            :loading="loading"
            @click="saveOperationSubmit()"
            v-if="handleType != 'edit' && form.is_operation_check"
            >保存并提交运营审核</el-button
          >
          <el-checkbox
            class="ml-5 -mt-1"
            v-model="form.is_notify"
            :true-label="1"
            :false-label="0"
            label="消息通知审核人员"
            size="large"
          />
        </span>
        <template v-else-if="handleType == 'development-audit'">
          <el-button type="primary" @click="handleAudit(true)">审核通过</el-button>
          <el-button @click="handleAudit(false)">审核未通过</el-button>
        </template>
        <template v-else>
          <el-button @click="close">关闭</el-button>
        </template>
      </template>
    </el-dialog>
    <ProfitTrial ref="ProfitTrialRef" @fee="updateFee"></ProfitTrial>
  </div>
</template>
<script setup name="AddModal" lang="jsx">
import api from "../api";
import { reactive, toRefs, getCurrentInstance, nextTick, ref, watch } from "vue";
import WangEditor from "@/components/WangEditor/index.vue";
import FileUpload from "@/components/FileUpload";
import Basic from "./BasicInfo/Basic.vue";
import Fee from "./Fee.vue";
import ProfitTrial from "./ProfitTrial.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "../../../../store/modules/user";

const { proxy } = getCurrentInstance();
const emits = defineEmits(["query"]);

const data = reactive({
  form: {
    submit_review: false,
    platform_name: "",
    is_notify: false,
    attribute_type: 1,
    specification: [
      {
        label: "颜色",
        value: [""],
      },
      {
        label: "尺寸",
        value: [""],
      },
    ],

    product_fee: [],
    competing_products_link: [""],
    is_gather: 0,
    is_operation_check: null,
  },
  visible: false,
  type: null,
  title: "",
  formRef: null,
  basicRef: null,
  ProfitTrialRef: null,
  content: "",
  rules: {
    recommended_platform: [{ trigger: "change", required: true, message: "请选择平台" }],
    recommended_site: [{ trigger: "change", required: true, message: "请选择站点" }],
  },
  handleType: null,
  load: false,
  estimated_product_gross_margin: 0,
  estimated_sale_gross_margin: 0,
  loading: false,
});

const {
  rules,
  form,
  visible,
  formRef,
  ProfitTrialRef,
  title,
  handleType,
  basicRef,
  load,
  estimated_product_gross_margin,
  estimated_sale_gross_margin,
  loading,
} = toRefs(data);

const loadings = reactive({
  form: false,
});

provide("handleType", handleType);
provide("form", form);

const statusMap = new Map([
  ["add", "新增"],
  ["edit", "编辑"],
  ["view", "查看"],
  ["copy", "复制"],
  ["development-audit", "开发审核"],
]);

const open = async (id, type) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  if (!id) {
    const u = useUserStore();
    const { userInfo } = u;
    nextTick(() => {
      form.value.developer_id = userInfo.user.user_id;
    });
  }
  title.value = statusMap.get(type);
  handleType.value = type;
  if (id) await getDetail(id, type);
  visible.value = true;
};

const getDetail = (id, type) => {
  loadings.form = true;
  api
    .getDetail({ productId: id })
    .then((res) => {
      form.value = res.data;
      form.value.competing_products_link =
        res.data.competing_products_link && res.data.competing_products_link.length
          ? res.data.competing_products_link
          : [""];
      form.value.product_category = form.value.product_category.map((i) => Number(i));

      form.value.product_fee = form.value.product_fee?.map((item) => {
        let suggest_prepare_count = item.suggest_prepare_count;
        if (type == "copy") {
          suggest_prepare_count = "";
          delete item.specified_operation_user_id;
          delete item.specified_operation_user_id_text;
          delete item.check_status;
          delete item.check_status_text;
          delete item.check_remark;
        }
        item.head_channel_id = item.head_channel_id || "";
        item.tail_channel_id = item.tail_channel_id || "";

        return {
          ...item,
          operation_user_id: item.operation_user_id == 0 ? null : item.operation_user_id,
          suggest_prepare_count,
        };
      });
      if (type == "copy") {
        delete form.value.id;
        delete form.value.sku_id;
        delete form.value.sku_id_text;
        delete form.value.sku_list;
        delete form.value.review_remark;
      }
      if (type == "development-audit") {
        form.value.specification = form.value.specification.map((i) => {
          i.valueOptions = i.value;
          return i;
        });
      }
    })
    .finally(() => {
      loadings.form = false;
    });
};

const openProfitTrial = (val) => {
  nextTick(() => {
    let length = form.value?.product_fee?.length || 0;
    let data = {
      is_operation_check: form.value.is_operation_check,
      refund_rate: 4,
      advertising_rate: 5,
      tariff_percent: "",
      site_country_code: "",
      other_fee_currency: "%",
    };
    ProfitTrialRef.value.open({ data, length });
  });
};

const updateFee = (fee) => {
  form.value.product_fee.push(fee);
};

const delFee = (index) => {
  form.value.product_fee.splice(index, 1);
};

// 保存
const save = (data = {}) => {
  const formData = Object.assign({}, form.value, data);
  formData.estimated_sale_gross_margin = Number(estimated_sale_gross_margin.value);
  formData.estimated_product_gross_margin = Number(estimated_product_gross_margin.value);

  if (!formRef.value) return;
  const validBasic = new Promise((resolve) => {
    proxy.$refs["basicRef"].validate((valid) => {
      if (valid) resolve();
    });
  });
  const validForm = new Promise((resolve) => {
    proxy.$refs["formRef"].validate((valid) => {
      if (valid) resolve();
    });
  });

  const messageArray = [];

  const platformSiteMap = new Map();
  formData.product_fee.forEach((item, index) => {
    const key = `${item.platform_code}-${item.site_text}`; // 假设 platform 和 site 是您用于识别平台和站点的属性
    if (platformSiteMap.has(key)) {
      messageArray.push(
        `推荐平台/站点重复: 第${index + 1}条数据与之前的数据平台/站点相同`
      );
    } else {
      platformSiteMap.set(key, true);
    }
    if (formData.is_operation_check == 1) {
      // 保留原有检查逻辑
      if (!item.operation_user_id) {
        messageArray.push(`推荐平台/站点: 第${index + 1}条数据,请选择运营人员`);
      }
    }
  });

  if (messageArray && messageArray.length) {
    ElMessageBox({
      title: "提示",
      message: () => <div>{messageArray.map((d) => h("p", null, d))}</div>,
    });
    return;
  }

  if (formData.attribute_type == 2) {
    const is_flag = formData.specification.some((i) => i.value?.length);
    if (!is_flag) {
      ElMessage.error("多属性规格属性不能为空,请选择");
      return;
    }
  }

  submitBefore();
  Promise.all([validBasic, validForm]).then(() => {
    loading.value = true;
    //全部验证通过
    if (formData.id) {
      api
        .update(formData)
        .then((res) => {
          ElMessage.success(res.message);
          emits("query");
          close();
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      api
        .add(formData)
        .then((res) => {
          ElMessage.success(res.message);
          emits("query");
          close();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};

const submitBefore = () => {
  form.value.competing_products_link = form.value.competing_products_link.filter((v) =>
    Boolean(v)
  );
};
// 保存审核
const saveSubmit = () => {
  if (!form.value.reviewer_id) {
    ElMessage.error("请选择审核人员");
    return;
  }
  save({
    submit_review: true,
  });
};

// 保存审核
const saveOperationSubmit = () => {
  save({
    is_operation: 1,
  });
};

const reset = () => {
  nextTick(() => {
    form.value = {
      submit_review: false,
      platform_name: "",
      is_notify: false,
      attribute_type: 1,
      specification: [
        {
          label: "颜色",
          value: [""],
        },
        {
          label: "尺寸",
          value: [""],
        },
      ],
      estimated_product_gross_margin: null,
      estimated_sale_gross_margin: null,
      product_fee: [],
      competing_products_link: [""],
      is_gather: 0,
      development_remark: "",
      product_category: [],
    };
  });
};

const close = () => {
  reset();
  visible.value = false;
};
const downloadUrl = (url) => {
  if (!url) return;
  let link = document.createElement("a");
  link.style.display = "none";
  link.href = url;
  link.setAttribute("download", "导出img");
  document.body.appendChild(link);
  link.click();
};

provide("form", form);

const handleAudit = (review_opinion) => {
  if (form.value.attribute_type == 2) {
    const is_flag = form.value.specification.some((i) => i.value?.length);
    if (!is_flag) {
      ElMessage.error("多属性规格属性不能为空,请选择");
      return;
    }
  }

  if (!review_opinion && !form.value.review_remark) {
    ElMessage.error("请填写审核备注");
    return;
  }

  const spu_specification = form.value.specification.length
    ? form.value.specification.map((item, index) => {
        const key_value = [];
        if (item.value && item.value.length) {
          item.value.map((i) => {
            key_value.push({
              language_id: 1,
              language_name: "中文",
              name: i,
              value: i,
              group: index + 1,
            });
          });
        }

        item.values = [
          {
            language_id: 1,
            language_name: "中文",
            group: index + 1,
            name: item.label,
            language_values: [...key_value],
          },
        ];
        return {
          group_name: item.label,
          values: item.values,
        };
      })
    : [];

  const specification = form.value.specification.map((i) => {
    delete i.valueOptions;
    return i;
  });

  api
    .review({
      product_ids: [form.value.id],
      review_opinion,
      review_remark: form.value.review_remark || "",
      spu_specification,
      specification: specification,
    })
    .then((res) => {
      ElMessage.success(res.message);
      emits("query");
      close();
    })
    .finally(() => {
      loading.value = false;
    });
};
defineExpose({ open });
</script>
<style lang="scss" scoped>
:deep(.develop-addmodal) {
  .el-dialog__body {
    padding-top: 16px;
  }
}

.title-style {
  font-size: 16px;
  font-weight: bold;
  color: var(--base-sub-text-color);
  padding: 10px 0;
  display: flex;
  align-items: center;

  .line {
    width: 2px;
    height: 14px;
    background: #3366f1;
    display: inline-block;
    margin-right: 4px;
  }
}

// 组合下拉框
.group-select {
  border: 1px solid var(--el-border-color);
  border-radius: 4px;

  .el-form-item--default {
    margin-bottom: 0;
  }

  .start-select,
  .end-select {
    .el-input__wrapper {
      border: none;
      box-shadow: none;
    }
  }

  .start-select {
    width: 150px;
    border-right: 1px solid var(--el-border-color);
    border-radius: 0;
  }

  .end-select {
    width: 150px;
  }
}

.rate-bg {
  background: var(--base-table-header-bg-color);
  border-radius: 4px;
  padding: 35px 138px;
  margin: 16px 0;
}
</style>
